<script setup lang="ts">
import { Error } from '@/components/Error'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'

const { push } = useRouter()

const permissionStore = usePermissionStore()

const errorClick = () => {
  try {
    // 检查是否有可用的路由
    const addRouters = permissionStore.getAddRouters || []
    if (addRouters && addRouters.length > 0) {
      // 查找第一个有效的非根路径路由
      const firstValidRoute = addRouters.find(
        (route) => route && route.path && route.path !== '/' && route.path !== '/404'
      )
      if (firstValidRoute && firstValidRoute.path) {
        console.log('404页面：跳转到有效路由:', firstValidRoute.path)
        push(firstValidRoute.path)
      } else {
        console.log('404页面：没有找到有效路由，跳转到根路径')
        push('/')
      }
    } else {
      console.log('404页面：没有可用路由，跳转到根路径')
      push('/')
    }
  } catch (error) {
    console.error('404页面：路由跳转失败:', error)
    // 如果路由跳转失败，尝试跳转到根路径
    try {
      push('/')
    } catch (fallbackError) {
      console.error('404页面：回退跳转也失败:', fallbackError)
      // 最后的回退方案：刷新页面
      window.location.href = '/'
    }
  }
}
</script>

<template>
  <Error @error-click="errorClick" />
</template>
